#!/bin/bash
mv /tmp/{flanneld,mk-docker-opts.sh} /usr/local/bin/
FLANNEL_OPTIONS="--etcd-endpoints=https://{{ groups.etcd[0] }}:2379,https://{{ groups.etcd[1] }}:2379,https://{{ groups.etcd[2] }}:2379 -etcd-cafile=/etc/etcd/ssl/ca.pem -etcd-certfile=/etc/etcd/ssl/server.pem -etcd-keyfile=/etc/etcd/ssl/server-key.pem"
cd /etc/etcd/ssl
etcdctl \
--ca-file=ca.pem --cert-file=server.pem --key-file=server-key.pem \
--endpoints="https://{{ groups.etcd[0] }}:2379,https://{{ groups.etcd[1] }}:2379,https://{{ groups.etcd[2] }}:2379" \
set /coreos.com/network/config  '{ "Network": "172.17.0.0/16", "Backend": {"Type": "vxlan"}}'

cat>{{FLANNEL_CONF}}<<EOF
FLANNEL_OPTIONS=$FLANNEL_OPTIONS
EOF
cat>/usr/lib/systemd/system/flanneld.service<<EOF
[Unit]
Description=Flanneld overlay address etcd agent
After=network-online.target network.target
Before=docker.service

[Service]
Type=notify
EnvironmentFile={{FLANNEL_CONF}}
ExecStart=/usr/local/bin/flanneld --ip-masq $FLANNEL_OPTIONS
ExecStartPost=/usr/local/bin/mk-docker-opts.sh -k DOCKER_NETWORK_OPTIONS -d /run/flannel/subnet.env
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF
